/*
 * @Author: zxc
 * @Date: 2021-01-30 09:28:33
 * @LastEditTime: 2021-01-30 20:38:29
 * @LastEditors: zxc
 * @Description: 
 */
const PENDING = "pending"
const FULFILLED = "fulfilled"
const REJECTED = "rejected"

class myPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject)
    } catch (err) {
      this.reject(err)
    }
  }
  status = PENDING
  value = undefined
  error = undefined
  successCallback = []
  failCallback = []
  catch (failCallback) {
    return this.then(undefined, failCallback)
  }
  resolve = value => {
    if (this.status !== PENDING) return
    //更改状态为成功
    this.status = FULFILLED
    //保存成功的值
    this.value = value
    // 判断是否存在成功回调，如存在，则调用 
    while (this.successCallback.length) {
      this.successCallback.shift()()
    }
  }
  reject = error => {
    if (this.status !== PENDING) return
    //更改状态为失败
    this.status = REJECTED
    //保存失败的原因
    this.error = error
    // 判断是否存在成功回调，如存在，则调用 
    while (this.failCallback.length) {
      this.failCallback.shift()()
    }
  }
  then(successCallback, failCallback) {
    successCallback = successCallback ? successCallback : value => value
    failCallback = failCallback ? failCallback : err => {
      throw err
    }
    let promise = new myPromise((resolve, reject) => {
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            // 判断 x 的值是普通值还是promise对象
            // 如果是普通值，直接调用 resolve
            // 如果是promise对象，查看promise对象返回的结果
            // 如果是promise对象返回的结果，决定调用resolve还是reject
            let x = successCallback(this.value)
            resolvePromise(x, resolve, reject)
          } catch (err) {
            reject(err)
          }
        }, 0);
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            // 判断 x 的值是普通值还是promise对象
            // 如果是普通值，直接调用 resolve
            // 如果是promise对象，查看promise对象返回的结果
            // 如果是promise对象返回的结果，决定调用resolve还是reject
            let x = failCallback(this.error)
            resolvePromise(x, resolve, reject)
          } catch (err) {
            reject(err)
          }
        }, 0);
      } else {
        // 等待状态,将成功和失败回调进行存储
        this.successCallback.push(() => {

          setTimeout(() => {
            try {
              // 判断 x 的值是普通值还是promise对象
              // 如果是普通值，直接调用 resolve
              // 如果是promise对象，查看promise对象返回的结果
              // 如果是promise对象返回的结果，决定调用resolve还是reject
              let x = successCallback(this.value)
              resolvePromise(x, resolve, reject)
            } catch (err) {
              reject(err)
            }
          }, 0);
        })
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              // 判断 x 的值是普通值还是promise对象
              // 如果是普通值，直接调用 resolve
              // 如果是promise对象，查看promise对象返回的结果
              // 如果是promise对象返回的结果，决定调用resolve还是reject
              let x = failCallback(this.error)
              resolvePromise(x, resolve, reject)
            } catch (err) {
              reject(err)
            }
          }, 0);
        })
      }
    });
    return promise
  }
  finally(callback) {
    return this.then(value => {
      return MyPromise.resolve(callback()).then(() => value);
    }, reason => {
      return MyPromise.resolve(callback()).then(() => {
        throw reason
      })
    })
  }
  static all(array) {
    let result = [];
    let index = 0;
    return new MyPromise((resolve, reject) => {
      function addData(key, value) {
        result[key] = value;
        index++;
        if (index === array.length) {
          resolve(result);
        }
      }
      for (let i = 0; i < array.length; i++) {
        let current = array[i];
        if (current instanceof MyPromise) {
          // promise 对象
          current.then(value => addData(i, value), reason => reject(reason))
        } else {
          // 普通值
          addData(i, array[i]);
        }
      }
    })
  }
  static resolve(value) {
    if (value instanceof MyPromise) return value;
    return new MyPromise(resolve => resolve(value));
  }
}

function resolvePromise(x, resolve, reject) {
  if (x instanceof myPromise) {
    x.then(resolve, reject)
  } else {
    resolve(x)
  }
}

export default myPromise